<template>
  <div class="search-section">
    <div class="search-wrapper">
      <div class="search-engine-selector">
        <button
          :class="{ active: searchEngine === 'google' }"
          @click="setSearchEngine('google')"
          title="使用 Google 搜索"
        >
          <img src="/google-icon.svg" alt="Google" class="engine-icon" />
        </button>
        <button
          :class="{ active: searchEngine === 'baidu' }"
          @click="setSearchEngine('baidu')"
          title="使用百度搜索"
        >
          <img src="/baidu-icon.svg" alt="Baidu" class="engine-icon" />
        </button>
      </div>
      <form class="search-bar" @submit.prevent="performSearch">
        <div class="input-container">
          <input
            ref="searchInput"
            type="text"
            v-model.trim="query"
            placeholder="搜索内容或输入网址（@开头强制作为URL）..."
            class="search-input"
            @input="onInputChange"
            @focus="handleFocus"
            @blur="handleBlur"
            @keydown="handleKeydown"
            autocomplete="off"
          />

          <!-- 建议下拉框 -->
          <div
            v-if="
              showSuggestions && (filteredSuggestions.length || query.trim())
            "
            class="suggestions-dropdown"
          >
            <div v-if="filteredSuggestions.length" class="suggestions-header">
              <div class="suggestion-types">
                <span v-if="searchSuggestions.length" class="suggestion-type">
                  <i class="fas fa-search"></i> 搜索建议
                </span>
                <span v-if="historySuggestions.length" class="suggestion-type">
                  <i class="fas fa-history"></i> 历史记录
                </span>
                <span v-if="bookmarkSuggestions.length" class="suggestion-type">
                  <i class="fas fa-bookmark"></i> 书签
                </span>
              </div>
            </div>
            <div
              v-if="!filteredSuggestions.length && query.trim()"
              class="no-suggestions"
            >
              <i class="fas fa-search suggestion-icon"></i>
              <span>按回车搜索 "{{ query }}"</span>
            </div>
            <div
              v-for="(suggestion, index) in filteredSuggestions"
              :key="index"
              :class="[
                'suggestion-item',
                { active: selectedSuggestionIndex === index },
              ]"
              @click="selectSuggestion(suggestion)"
            >
              <i
                :class="getSuggestionIcon(suggestion.type)"
                class="suggestion-icon"
              ></i>
              <div class="suggestion-content">
                <div class="suggestion-title">{{ suggestion.title }}</div>
                <div v-if="suggestion.url" class="suggestion-url">
                  {{ suggestion.url }}
                </div>
              </div>
              <div
                v-if="suggestion.type === 'history'"
                class="suggestion-actions"
              >
                <button
                  @click.stop="removeFromHistory(suggestion)"
                  class="remove-btn"
                  title="从历史记录中删除"
                >
                  <i class="fas fa-times"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
        <button
          type="submit"
          :class="['search-button', { focused: isSearchFocused }]"
          title="搜索"
        >
          <i class="fas fa-search"></i>
        </button>
      </form>

      <!-- 书签管理按钮 -->
      <!-- <div class="bookmark-controls">
        <button
          @click="showBookmarkModal = true"
          class="bookmark-btn"
          title="书签管理"
        >
          <i class="fas fa-bookmark"></i>
        </button>
      </div> -->
      <!-- 新增设置按钮 -->
      <!-- <div class="settings-controls">
        <button
          @click="showSettingsModal = true"
          class="settings-btn-round"
          title="设置"
        >
          <i class="fas fa-cog"></i>
        </button>
      </div> -->
    </div>

    <!-- 书签管理模态框 -->
    <div
      v-if="showBookmarkModal"
      class="modal-overlay"
      @click="showBookmarkModal = false"
    >
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>书签管理</h3>
          <button @click="showBookmarkModal = false" class="close-btn">
            <i class="fas fa-times"></i>
          </button>
        </div>

        <div class="modal-body">
          <!-- 书签导入 -->
          <div class="bookmark-section">
            <h4>导入书签</h4>
            <div class="import-controls">
              <input
                ref="fileInput"
                type="file"
                accept=".html"
                @change="handleFileImport"
                style="display: none"
              />
              <button @click="$refs.fileInput.click()" class="btn-primary">
                <i class="fas fa-upload"></i>
                导入HTML文件
              </button>
              <span class="import-help"
                >支持Chrome、Firefox等浏览器导出的书签文件</span
              >
            </div>
          </div>

          <!-- 书签操作 -->
          <div class="bookmark-section">
            <h4>操作</h4>
            <div class="operation-controls">
              <button @click="exportBookmarks" class="btn-secondary">
                <i class="fas fa-download"></i>
                导出书签
              </button>
              <button @click="clearBookmarks" class="btn-danger">
                <i class="fas fa-trash"></i>
                清空书签
              </button>
              <button @click="mergeBookmarks" class="btn-success">
                <i class="fas fa-merge"></i>
                合并重复项
              </button>
            </div>
          </div>

          <!-- 文件夹操作 -->
          <div class="bookmark-section">
            <h4>文件夹操作</h4>
            <div class="folder-controls">
              <button @click="expandAllFolders" class="btn-outline">
                <i class="fas fa-expand-arrows-alt"></i>
                全部展开
              </button>
              <button @click="collapseAllFolders" class="btn-outline">
                <i class="fas fa-compress-arrows-alt"></i>
                全部折叠
              </button>
            </div>
          </div>

          <!-- 书签列表 -->
          <div class="bookmark-section">
            <h4>已保存的书签 ({{ bookmarks.length }})</h4>
            <div class="bookmark-list">
              <!-- 按文件夹分组显示 -->
              <div
                v-for="(folderData, folderName) in groupedAllBookmarks"
                :key="folderName"
                class="folder-group"
              >
                <div class="folder-header" @click="toggleFolder(folderName)">
                  <i
                    :class="[
                      'fas',
                      folderExpanded[folderName]
                        ? 'fa-folder-open'
                        : 'fa-folder',
                    ]"
                  ></i>
                  <span class="folder-name">{{ folderName || "未分类" }}</span>
                  <span class="folder-count">({{ folderData.length }})</span>
                  <i
                    :class="[
                      'fas',
                      'folder-toggle',
                      folderExpanded[folderName]
                        ? 'fa-chevron-down'
                        : 'fa-chevron-right',
                    ]"
                  ></i>
                </div>
                <div v-show="folderExpanded[folderName]" class="folder-content">
                  <div
                    v-for="bookmark in folderData"
                    :key="bookmark.id"
                    class="bookmark-item"
                  >
                    <div class="bookmark-info">
                      <div class="bookmark-title">{{ bookmark.title }}</div>
                      <div class="bookmark-url">{{ bookmark.url }}</div>
                    </div>
                    <div class="bookmark-actions">
                      <button
                        @click="openBookmark(bookmark)"
                        class="action-btn"
                        title="打开"
                      >
                        <i class="fas fa-external-link-alt"></i>
                      </button>
                      <button
                        @click="removeBookmark(bookmark)"
                        class="action-btn remove"
                        title="删除"
                      >
                        <i class="fas fa-trash"></i>
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 设置弹窗 -->
    <div
      v-if="showSettingsModal"
      class="modal-overlay"
      @click="showSettingsModal = false"
    >
      <div class="modal-content settings-modal" @click.stop>
        <div class="settings-modal-header">
          <span class="settings-modal-title"
            ><i class="fas fa-cog"></i> 设置</span
          >
          <button
            @click="showSettingsModal = false"
            class="settings-modal-close"
          >
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="settings-modal-body">
          <div class="settings-group">
            <label for="apiBaseUrl" class="settings-label">API请求地址</label>
            <input
              id="apiBaseUrl"
              v-model="apiBaseUrl"
              class="settings-input"
              placeholder="如 http://localhost:3001"
            />
          </div>
          <div class="settings-group">
            <label class="settings-label">背景设置</label>
            <div class="background-options">
              <div class="option-group">
                <label class="radio-label">
                  <input
                    type="radio"
                    name="bgType"
                    value="theme"
                    :checked="bgType === 'theme'"
                    @change="handleBgTypeChange('theme')"
                  />
                  系统皮肤
                </label>
                <div class="theme-options" v-show="bgType === 'theme'">
                  <button
                    v-for="theme in themes"
                    :key="theme.value"
                    :class="[
                      'theme-select-btn',
                      { active: currentTheme === theme.value },
                    ]"
                    @click="switchTheme(theme.value)"
                  >
                    {{ theme.label }}
                  </button>
                </div>
              </div>

              <div class="option-group">
                <label class="radio-label">
                  <input
                    type="radio"
                    name="bgType"
                    value="custom"
                    :checked="bgType === 'custom'"
                    @change="handleBgTypeChange('custom')"
                  />
                  自定义背景
                </label>
                <div class="custom-bg-options" v-show="bgType === 'custom'">
                  <input
                    v-model="bgUrl"
                    class="settings-input"
                    placeholder="图片URL"
                  />
                  <button
                    @click="$refs.bgFileInput.click()"
                    class="settings-upload-btn"
                  >
                    上传图片
                  </button>
                  <input
                    type="file"
                    ref="bgFileInput"
                    style="display: none"
                    accept="image/*"
                    @change="handleBgFileChange"
                  />
                  <div v-if="bgUrl" class="settings-bg-preview">
                    <img :src="bgUrl" />
                    <button class="remove-bg-btn" @click="removeBgImage">
                      <i class="fas fa-times"></i>
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <button @click="saveApiBaseUrl" class="settings-save-btn">
            保存
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, nextTick } from "vue";
import { getApiBaseUrl, setApiBaseUrl } from "../config/index.js";

const query = ref("");
const searchEngine = ref("google");
const showSuggestions = ref(false);
const selectedSuggestionIndex = ref(-1);
const showBookmarkModal = ref(false);
const searchInput = ref(null);
const isSearchFocused = ref(false);
const showSettingsModal = ref(false);
const apiBaseUrl = ref("");
const bgUrl = ref("");
const bgFileInput = ref(null);
const bgType = ref(localStorage.getItem("bgType") || "theme");

// 数据存储
const searchHistory = ref([]);
const bookmarks = ref([]);

// 建议相关状态
const searchSuggestions = ref([]);
const historySuggestions = ref([]);
const bookmarkSuggestions = ref([]);

// 文件夹展开状态
const folderExpanded = ref({});

// 新增：扩展模式下自动获取书签和历史
const isExtension =
  typeof chrome !== "undefined" && chrome.bookmarks && chrome.history;
const extensionBookmarks = ref([]);
const extensionHistory = ref([]);

// 新增：无输入时展示最近历史
const recentHistorySuggestions = ref([]);

// 辅助：递归提取浏览器书签为平铺数组
function flattenChromeBookmarks(tree, folder = "") {
  let result = [];
  tree.forEach((node) => {
    if (node.url) {
      result.push({
        id: node.id,
        title: node.title,
        url: node.url,
        folder: folder,
        isChrome: true,
      });
    } else if (node.children) {
      const folderName = node.title || folder;
      result = result.concat(flattenChromeBookmarks(node.children, folderName));
    }
  });
  return result;
}

// 合并所有书签
const allBookmarks = computed(() => {
  let chromeBookmarks = [];
  if (isExtension && window.extensionBookmarks) {
    chromeBookmarks = flattenChromeBookmarks(window.extensionBookmarks);
  }
  // 合并本地和浏览器书签
  return [
    ...bookmarks.value.map((b) => ({ ...b, isChrome: false })),
    ...chromeBookmarks,
  ];
});

// 合并所有历史
const allHistory = computed(() => {
  let chromeHistory = [];
  if (isExtension && window.extensionHistory) {
    chromeHistory = window.extensionHistory.map((h) => ({
      id: h.id,
      title: h.title || h.url,
      url: h.url,
      isChrome: true,
    }));
  }
  return [
    ...searchHistory.value.map((h) => ({ ...h, isChrome: false })),
    ...chromeHistory,
  ];
});

// 书签管理弹窗分组渲染
const groupedAllBookmarks = computed(() => {
  const groups = { 本地书签: [], 浏览器书签: [] };
  allBookmarks.value.forEach((b) => {
    if (b.isChrome) {
      groups["浏览器书签"].push(b);
    } else {
      groups["本地书签"].push(b);
    }
  });
  return groups;
});

// 初始化
onMounted(async () => {
  loadSearchHistory();
  loadBookmarks();
  // 自动聚焦搜索框（兼容新标签页）
  await nextTick();
  setTimeout(() => {
    if (searchInput.value) {
      searchInput.value.focus();
    }
  }, 100);
  window.addEventListener("load", () => {
    if (searchInput.value) {
      searchInput.value.focus();
    }
  });

  // 如果没有历史记录，添加一些示例数据
  if (searchHistory.value.length === 0) {
    const sampleHistory = [
      {
        id: 1,
        query: "Vue.js 教程",
        url: "https://cn.vuejs.org/",
        timestamp: Date.now() - 86400000,
      },
      {
        id: 2,
        query: "JavaScript",
        url: "https://developer.mozilla.org/zh-CN/docs/Web/JavaScript",
        timestamp: Date.now() - 172800000,
      },
    ];
    searchHistory.value = sampleHistory;
    localStorage.setItem("searchHistory", JSON.stringify(searchHistory.value));
  }

  // 如果没有书签，添加一些示例数据
  if (bookmarks.value.length === 0) {
    const sampleBookmarks = [
      {
        id: 1,
        title: "Vue.js 官网",
        url: "https://cn.vuejs.org/",
        folder: "开发工具",
        addDate: Date.now(),
      },
      {
        id: 2,
        title: "GitHub",
        url: "https://github.com",
        folder: "开发工具",
        addDate: Date.now(),
      },
      {
        id: 3,
        title: "MDN Web Docs",
        url: "https://developer.mozilla.org/",
        folder: "文档",
        addDate: Date.now(),
      },
      {
        id: 4,
        title: "百度",
        url: "https://www.baidu.com",
        folder: "", // 未分类书签
        addDate: Date.now(),
      },
      {
        id: 5,
        title: "Google",
        url: "https://www.google.com",
        folder: "", // 未分类书签
        addDate: Date.now(),
      },
    ];
    bookmarks.value = sampleBookmarks;
    localStorage.setItem("bookmarks", JSON.stringify(bookmarks.value));
  }

  // 初始化建议
  updateSuggestions();

  // 添加全局键盘快捷键监听
  document.addEventListener("keydown", handleGlobalKeydown);

  apiBaseUrl.value = await getApiBaseUrl();
  // 读取背景图
  const localBg = localStorage.getItem("customBgUrl");
  if (localBg) bgUrl.value = localBg;

  if (isExtension) {
    // 获取书签
    chrome.bookmarks.getTree((tree) => {
      extensionBookmarks.value = tree;
    });
    // 获取历史
    chrome.history.search({ text: "", maxResults: 50 }, (results) => {
      extensionHistory.value = results;
    });
  }

  // 初始化主题
  const saved = localStorage.getItem("theme");
  if (saved && themes.some((t) => t.value === saved)) {
    switchTheme(saved);
  }

  // 初始化背景类型
  const savedBgType = localStorage.getItem("bgType");
  if (savedBgType) {
    bgType.value = savedBgType;
  } else {
    // 如果有自定义背景图，则设置为custom类型
    bgType.value = bgUrl.value ? "custom" : "theme";
  }
});

onUnmounted(() => {
  // 移除全局键盘事件监听器
  document.removeEventListener("keydown", handleGlobalKeydown);
});

// 计算属性
const filteredSuggestions = computed(() => {
  const all = [
    ...searchSuggestions.value,
    ...historySuggestions.value,
    ...bookmarkSuggestions.value,
  ];
  return all.slice(0, 8); // 限制显示数量
});

const displayBookmarks = computed(() => {
  return bookmarks.value.slice(0, 50); // 限制显示数量
});

// 按文件夹分组的书签
const groupedBookmarks = computed(() => {
  const groups = {};

  bookmarks.value.forEach((bookmark) => {
    const folderName = bookmark.folder || "";
    if (!groups[folderName]) {
      groups[folderName] = [];
    }
    groups[folderName].push(bookmark);
  });

  // 按文件夹名称排序，未分类放在最后
  const sortedGroups = {};
  const sortedKeys = Object.keys(groups).sort((a, b) => {
    if (a === "") return 1; // 未分类放最后
    if (b === "") return -1;
    return a.localeCompare(b);
  });

  sortedKeys.forEach((key) => {
    sortedGroups[key] = groups[key];
    // 初始化文件夹展开状态
    if (!(key in folderExpanded.value)) {
      folderExpanded.value[key] = true; // 默认展开
    }
  });

  // 调试信息
  console.log("分组结果:", sortedGroups);
  console.log("文件夹列表:", sortedKeys);
  console.log("未分类书签数量:", groups[""] ? groups[""].length : 0);

  // 额外调试：显示每个分组的详细信息
  Object.keys(groups).forEach((folderName) => {
    const displayName = folderName === "" ? "未分类" : folderName;
    console.log(`📁 ${displayName}: ${groups[folderName].length} 个书签`);
    if (folderName === "") {
      console.log(
        "未分类书签详情:",
        groups[folderName].map((b) => b.title)
      );
    }
  });

  return sortedGroups;
});

// 搜索引擎设置
const setSearchEngine = (engine) => {
  searchEngine.value = engine;
  localStorage.setItem("searchEngine", engine);
};

// URL验证
const isValidUrl = (string) => {
  try {
    // 使用更安全的URL验证方法
    if (string.startsWith("http://") || string.startsWith("https://")) {
      new URL(string);
      return true;
    } else {
      // 简单的域名验证
      const domainPattern =
        /^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]?\.[a-zA-Z]{2,}$/;
      return domainPattern.test(string);
    }
  } catch (e) {
    return false;
  }
};

// 输入变化处理
const onInputChange = () => {
  updateSuggestions();
  // 根据输入内容控制建议显示
  if (query.value.trim()) {
    showSuggestions.value = true;
  } else {
    // 无输入时也展示最近历史
    updateRecentHistorySuggestions();
    showSuggestions.value = true;
  }
};

// 新增：无输入时展示最近历史
const updateRecentHistorySuggestions = () => {
  // 取最近10条历史（本地+浏览器）
  recentHistorySuggestions.value = allHistory.value
    .slice(0, 10)
    .map((item) => ({
      type: item.isChrome ? "chrome-history" : "history",
      title: item.title,
      url: item.url,
      data: item,
    }));
};

// 更新建议
const updateSuggestions = () => {
  const searchTerm = query.value.toLowerCase().trim();
  if (!searchTerm) {
    historySuggestions.value = [];
    bookmarkSuggestions.value = [];
    searchSuggestions.value = [];
    return;
  }

  // 历史记录建议（本地+浏览器）
  historySuggestions.value = allHistory.value
    .filter(
      (item) =>
        (item.title && item.title.toLowerCase().includes(searchTerm)) ||
        (item.url && item.url.toLowerCase().includes(searchTerm))
    )
    .slice(0, 3)
    .map((item) => ({
      type: item.isChrome ? "chrome-history" : "history",
      title: item.title,
      url: item.url,
      data: item,
    }));
  // 书签建议（本地+浏览器）
  bookmarkSuggestions.value = allBookmarks.value
    .filter(
      (bookmark) =>
        bookmark.title.toLowerCase().includes(searchTerm) ||
        bookmark.url.toLowerCase().includes(searchTerm)
    )
    .slice(0, 3)
    .map((bookmark) => ({
      type: bookmark.isChrome ? "chrome-bookmark" : "bookmark",
      title: bookmark.title,
      url: bookmark.url,
      data: bookmark,
    }));
  // 搜索建议
  if (searchTerm.length > 0) {
    if (query.value.trim().startsWith("@")) {
      const urlPart = query.value.trim().substring(1);
      searchSuggestions.value = [
        {
          type: "url",
          title: `打开网址: ${urlPart}`,
          url: urlPart,
          data: { query: query.value },
        },
      ];
    } else {
      searchSuggestions.value = [
        {
          type: "search",
          title: `搜索 \"${query.value}\"`,
          url: null,
          data: { query: query.value },
        },
        {
          type: "translate",
          title: `翻译 \"${query.value}\"`,
          url: null,
          data: { query: query.value },
        },
      ];
    }
  } else {
    searchSuggestions.value = [];
  }
};

// 获取建议图标
const getSuggestionIcon = (type) => {
  switch (type) {
    case "history":
    case "chrome-history":
      return "fas fa-history";
    case "bookmark":
    case "chrome-bookmark":
      return "fas fa-bookmark";
    case "search":
      return "fas fa-search";
    case "translate":
      return "fas fa-language";
    case "url":
      return "fas fa-external-link-alt";
    default:
      return "fas fa-globe";
  }
};

// 全局键盘快捷键处理
const handleGlobalKeydown = (e) => {
  // Ctrl+F 或 Cmd+F 聚焦搜索框
  if ((e.ctrlKey || e.metaKey) && e.key === "f") {
    e.preventDefault();
    if (searchInput.value) {
      searchInput.value.focus();
      searchInput.value.select(); // 选中所有文本
    }
    return;
  }

  // ESC 清空搜索并失去焦点
  if (e.key === "Escape" && document.activeElement === searchInput.value) {
    query.value = "";
    showSuggestions.value = false;
    searchInput.value.blur();
    return;
  }
};

// 键盘导航
const handleKeydown = (e) => {
  if (!showSuggestions.value || !filteredSuggestions.value.length) return;

  switch (e.key) {
    case "ArrowDown":
      e.preventDefault();
      e.stopPropagation();
      selectedSuggestionIndex.value = Math.min(
        selectedSuggestionIndex.value + 1,
        filteredSuggestions.value.length - 1
      );
      scrollToSelectedSuggestion();
      break;
    case "ArrowUp":
      e.preventDefault();
      e.stopPropagation();
      selectedSuggestionIndex.value = Math.max(
        selectedSuggestionIndex.value - 1,
        -1
      );
      scrollToSelectedSuggestion();
      break;
    case "Enter":
      if (selectedSuggestionIndex.value >= 0) {
        e.preventDefault();
        e.stopPropagation();
        selectSuggestion(
          filteredSuggestions.value[selectedSuggestionIndex.value]
        );
      }
      break;
    case "Escape":
      e.preventDefault();
      e.stopPropagation();
      showSuggestions.value = false;
      selectedSuggestionIndex.value = -1;
      searchInput.value.blur();
      break;
  }
};

// 滚动到选中的建议项
const scrollToSelectedSuggestion = () => {
  nextTick(() => {
    if (selectedSuggestionIndex.value >= 0) {
      const suggestionsList = document.querySelector(".suggestions-dropdown");
      const selectedItem = document.querySelector(".suggestion-item.active");

      if (suggestionsList && selectedItem) {
        // 计算相对位置，手动控制滚动，避免影响页面
        const containerTop = suggestionsList.scrollTop;
        const containerHeight = suggestionsList.clientHeight;
        const itemTop = selectedItem.offsetTop;
        const itemHeight = selectedItem.offsetHeight;

        // 检查是否需要滚动
        if (itemTop < containerTop) {
          // 选中项在可视区域上方，滚动到顶部
          suggestionsList.scrollTo({
            top: itemTop,
            behavior: "smooth",
          });
        } else if (itemTop + itemHeight > containerTop + containerHeight) {
          // 选中项在可视区域下方，滚动到底部
          suggestionsList.scrollTo({
            top: itemTop + itemHeight - containerHeight,
            behavior: "smooth",
          });
        }
      }
    }
  });
};

// 选择建议
const selectSuggestion = (suggestion) => {
  if (suggestion.type === "bookmark" || suggestion.type === "chrome-bookmark") {
    openUrl(suggestion.url);
  } else if (
    suggestion.type === "history" ||
    suggestion.type === "chrome-history"
  ) {
    if (suggestion.url) {
      openUrl(suggestion.url);
    } else {
      query.value = suggestion.title;
      performSearch();
    }
  } else if (suggestion.type === "translate") {
    // 直接执行翻译
    const translateUrl = `https://translate.google.com/?sl=auto&tl=zh&text=${encodeURIComponent(
      query.value
    )}`;
    openUrl(translateUrl);
    saveToHistory({ query: query.value, url: translateUrl });
  } else {
    query.value = suggestion.title.replace('搜索 "', "").replace('"', "");
    performSearch();
  }
  closeSuggestions();
};

// 获得焦点处理
const handleFocus = () => {
  isSearchFocused.value = true;
  if (query.value.trim()) {
    showSuggestions.value = true;
  } else {
    updateRecentHistorySuggestions();
    showSuggestions.value = true;
  }
};

// 失去焦点处理
const handleBlur = () => {
  isSearchFocused.value = false;
  setTimeout(() => {
    showSuggestions.value = false;
    selectedSuggestionIndex.value = -1;
  }, 150);
};

// 关闭建议
const closeSuggestions = () => {
  showSuggestions.value = false;
  selectedSuggestionIndex.value = -1;
};

// 执行搜索
const performSearch = () => {
  if (!query.value) return;

  let searchQuery = query.value.trim();

  // 检查是否以@开头，表示强制作为URL处理
  if (searchQuery.startsWith("@")) {
    let url = searchQuery.substring(1); // 去掉@符号
    if (!url.startsWith("http://") && !url.startsWith("https://")) {
      url = "https://" + url;
    }
    openUrl(url);
    return;
  }

  // 新增：识别 git ssh 地址并跳转
  // 例如 git@gitlab.in.ys4fun.com:platform/client/web/pipeline.git
  const gitSshPattern = /^git@([\w.-]+):(.*?)(?:\.git)?$/;
  const match = searchQuery.match(gitSshPattern);
  if (match) {
    // 组装为 https://host/路径（去掉.git）
    let host = match[1];
    let path = match[2].replace(/\.git$/, "");
    let url = `https://${host}/${path}`;
    openUrl(url);
    return;
  }

  // 检查是否是URL
  if (isValidUrl(searchQuery)) {
    let url = searchQuery;
    if (!url.startsWith("http://") && !url.startsWith("https://")) {
      url = "https://" + url;
    }
    openUrl(url);
    return;
  }

  // 执行搜索
  const urls = {
    google: `https://www.google.com/search?q=${encodeURIComponent(
      searchQuery
    )}`,
    baidu: `https://www.baidu.com/s?wd=${encodeURIComponent(searchQuery)}`,
  };

  const searchUrl = urls[searchEngine.value];
  openUrl(searchUrl);

  // 保存到历史记录
  saveToHistory({ query: searchQuery, url: searchUrl });
  closeSuggestions();
};

// 打开URL
const openUrl = (url) => {
  window.location.href = url;
  saveToHistory({ query: query.value || url, url });
};

// 保存搜索历史
const saveToHistory = (item) => {
  const historyItem = {
    ...item,
    timestamp: Date.now(),
    id: Date.now() + Math.random(),
  };

  // 去重
  const existingIndex = searchHistory.value.findIndex(
    (h) => h.query === item.query && h.url === item.url
  );

  if (existingIndex >= 0) {
    searchHistory.value.splice(existingIndex, 1);
  }

  searchHistory.value.unshift(historyItem);

  // 限制历史记录数量
  if (searchHistory.value.length > 100) {
    searchHistory.value = searchHistory.value.slice(0, 100);
  }

  localStorage.setItem("searchHistory", JSON.stringify(searchHistory.value));
};

// 从历史记录中删除
const removeFromHistory = (suggestion) => {
  const index = searchHistory.value.findIndex(
    (h) => h.id === suggestion.data.id
  );
  if (index >= 0) {
    searchHistory.value.splice(index, 1);
    localStorage.setItem("searchHistory", JSON.stringify(searchHistory.value));
    updateSuggestions();
  }
};

// 加载搜索历史
const loadSearchHistory = () => {
  try {
    const saved = localStorage.getItem("searchHistory");
    if (saved) {
      searchHistory.value = JSON.parse(saved);
    }
  } catch (e) {
    console.error("Failed to load search history:", e);
  }

  // 加载搜索引擎设置
  const savedEngine = localStorage.getItem("searchEngine");
  if (savedEngine) {
    searchEngine.value = savedEngine;
  }
};

// 书签相关功能
const loadBookmarks = () => {
  try {
    const saved = localStorage.getItem("bookmarks");
    if (saved) {
      bookmarks.value = JSON.parse(saved);
    }
  } catch (e) {
    console.error("Failed to load bookmarks:", e);
  }
};

const saveBookmarks = () => {
  localStorage.setItem("bookmarks", JSON.stringify(bookmarks.value));
};

// 处理文件导入
const handleFileImport = (event) => {
  const file = event.target.files[0];
  if (!file) return;

  const reader = new FileReader();
  reader.onload = (e) => {
    try {
      parseBookmarksHTML(e.target.result);
    } catch (err) {
      alert("书签文件解析失败，请确保文件格式正确");
      console.error("Bookmark import error:", err);
    }
  };
  reader.readAsText(file);
};

// 解析书签HTML
const parseBookmarksHTML = (html) => {
  const newBookmarks = [];
  let folderStack = []; // 用于处理嵌套文件夹
  let currentFolder = ""; // 当前所在文件夹

  console.log("开始解析书签文件...");

  // 使用更可靠的逐行解析方法
  const lines = html.split("\n");

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i].trim();

    // 检测文件夹开始（H3 标签）
    const folderMatch = line.match(/<H3[^>]*>(.*?)<\/H3>/i);
    if (folderMatch) {
      const folderName = folderMatch[1].trim();

      // 跳过顶级的"书签栏"文件夹，将其内容视为根目录
      if (
        folderName === "书签栏" ||
        folderName === "Bookmarks Bar" ||
        folderName === "Bookmarks"
      ) {
        console.log(`跳过顶级文件夹: "${folderName}"`);
        folderStack.push("ROOT"); // 标记为根目录
        continue;
      }

      // 保存当前文件夹到堆栈
      folderStack.push(currentFolder);
      currentFolder = folderName;
      console.log(
        `进入文件夹: "${currentFolder}" (堆栈深度: ${folderStack.length})`
      );
      continue;
    }

    // 检测文件夹结束（</DL> 标签）
    if (line.includes("</DL>")) {
      // 退出当前文件夹
      if (folderStack.length > 0) {
        const previousFolder = folderStack.pop();
        if (previousFolder === "ROOT") {
          currentFolder = "";
          console.log(`退出根目录，当前文件夹: "未分类"`);
        } else {
          currentFolder = previousFolder;
          console.log(`退出文件夹，返回到: "${currentFolder || "未分类"}"`);
        }
      } else {
        currentFolder = "";
        console.log(`退出到根目录（未分类）`);
      }
      continue;
    }

    // 检测书签（A 标签）
    const linkMatch = line.match(/<A\s+HREF="([^"]+)"[^>]*>(.*?)<\/A>/i);
    if (linkMatch) {
      const url = linkMatch[1];
      const title = linkMatch[2].trim();

      // 提取 ADD_DATE 属性
      const addDateMatch = line.match(/ADD_DATE="(\d+)"/i);
      const addDate = addDateMatch
        ? parseInt(addDateMatch[1]) * 1000
        : Date.now();

      const bookmark = {
        id: Date.now() + Math.random(),
        title: title || url,
        url: url,
        folder: currentFolder, // 这里 currentFolder 可能是空字符串，这是正常的
        addDate: addDate,
      };

      newBookmarks.push(bookmark);
      console.log(
        `添加书签: "${title}" -> "${
          currentFolder || "未分类"
        }" (当前文件夹状态: "${currentFolder}", 堆栈深度: ${
          folderStack.length
        })`
      );

      // 额外调试信息
      if (currentFolder === "") {
        console.log(`⚠️ 发现未分类书签: ${title}`);
      }
    }
  }

  // 如果上面的方法没有找到书签，尝试DOM解析作为备用
  if (newBookmarks.length === 0) {
    console.log("逐行解析失败，尝试DOM解析...");
    try {
      const parser = new DOMParser();
      const doc = parser.parseFromString(html, "text/html");
      const links = doc.querySelectorAll("A[href]");

      for (const link of links) {
        if (link.href && link.href.startsWith("http")) {
          // 查找前面的 H3 作为文件夹名
          let folder = "";
          let parent = link.parentElement;

          while (parent && parent !== doc.body) {
            const h3 = parent.querySelector("H3");
            if (h3) {
              folder = h3.textContent.trim();
              break;
            }
            parent = parent.parentElement;
          }

          const bookmark = {
            id: Date.now() + Math.random(),
            title: link.textContent.trim() || link.href,
            url: link.href,
            folder: folder,
            addDate: link.getAttribute("ADD_DATE")
              ? parseInt(link.getAttribute("ADD_DATE")) * 1000
              : Date.now(),
          };
          newBookmarks.push(bookmark);
        }
      }
    } catch (error) {
      console.error("DOM解析也失败:", error);
    }
  }

  if (newBookmarks.length === 0) {
    alert("未找到有效的书签数据");
    return [];
  }

  // 打印调试信息
  console.log(`解析到 ${newBookmarks.length} 个书签`);
  console.log(
    "书签详情:",
    newBookmarks.slice(0, 5).map((b) => ({ title: b.title, folder: b.folder }))
  );

  // 合并到现有书签
  const existingUrls = new Set(bookmarks.value.map((b) => b.url));
  const uniqueBookmarks = newBookmarks.filter((b) => !existingUrls.has(b.url));

  bookmarks.value.push(...uniqueBookmarks);
  saveBookmarks();

  alert(
    `成功导入 ${uniqueBookmarks.length} 个书签（共找到 ${newBookmarks.length} 个书签，包含文件夹结构）`
  );

  return newBookmarks;
};

// 导出书签
const exportBookmarks = () => {
  if (bookmarks.value.length === 0) {
    alert("没有书签可导出");
    return;
  }

  let html = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<TITLE>Bookmarks</TITLE>
<H1>Bookmarks</H1>
<DL><p>
`;

  // 按文件夹分组
  const folders = {};
  const noFolder = [];

  bookmarks.value.forEach((bookmark) => {
    if (bookmark.folder && bookmark.folder.trim()) {
      if (!folders[bookmark.folder]) {
        folders[bookmark.folder] = [];
      }
      folders[bookmark.folder].push(bookmark);
    } else {
      noFolder.push(bookmark);
    }
  });

  // 生成HTML - 按文件夹名排序
  const sortedFolders = Object.keys(folders).sort();
  sortedFolders.forEach((folderName) => {
    html += `    <DT><H3 ADD_DATE="${Math.floor(
      Date.now() / 1000
    )}" LAST_MODIFIED="${Math.floor(Date.now() / 1000)}">${folderName}</H3>\n`;
    html += `    <DD><DL><p>\n`;
    folders[folderName].forEach((bookmark) => {
      const addDate = bookmark.addDate
        ? Math.floor(bookmark.addDate / 1000)
        : Math.floor(Date.now() / 1000);
      html += `        <DT><A HREF="${bookmark.url}" ADD_DATE="${addDate}">${bookmark.title}</A>\n`;
    });
    html += `    </DL><p>\n`;
  });

  // 无文件夹的书签
  if (noFolder.length > 0) {
    noFolder.forEach((bookmark) => {
      const addDate = bookmark.addDate
        ? Math.floor(bookmark.addDate / 1000)
        : Math.floor(Date.now() / 1000);
      html += `    <DT><A HREF="${bookmark.url}" ADD_DATE="${addDate}">${bookmark.title}</A>\n`;
    });
  }

  html += "</DL><p>";

  // 下载文件
  const blob = new Blob([html], { type: "text/html;charset=utf-8" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `bookmarks_${new Date().toISOString().split("T")[0]}.html`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);

  alert(
    `成功导出 ${bookmarks.value.length} 个书签，包含 ${sortedFolders.length} 个文件夹`
  );
};

// 清空书签
const clearBookmarks = () => {
  if (confirm("确定要清空所有书签吗？此操作不可恢复。")) {
    bookmarks.value = [];
    saveBookmarks();
  }
};

// 合并重复书签
const mergeBookmarks = () => {
  const seen = new Set();
  const unique = [];

  bookmarks.value.forEach((bookmark) => {
    if (!seen.has(bookmark.url)) {
      seen.add(bookmark.url);
      unique.push(bookmark);
    }
  });

  const removedCount = bookmarks.value.length - unique.length;
  bookmarks.value = unique;
  saveBookmarks();

  alert(`已删除 ${removedCount} 个重复书签`);
};

// 打开书签
const openBookmark = (bookmark) => {
  openUrl(bookmark.url);
  showBookmarkModal.value = false;
};

// 删除书签
const removeBookmark = (bookmark) => {
  const index = bookmarks.value.findIndex((b) => b.id === bookmark.id);
  if (index >= 0) {
    bookmarks.value.splice(index, 1);
    saveBookmarks();
  }
};

// 切换文件夹展开状态
const toggleFolder = (folderName) => {
  folderExpanded.value[folderName] = !folderExpanded.value[folderName];
};

// 展开所有文件夹
const expandAllFolders = () => {
  Object.keys(groupedBookmarks.value).forEach((folderName) => {
    folderExpanded.value[folderName] = true;
  });
};

// 折叠所有文件夹
const collapseAllFolders = () => {
  Object.keys(groupedBookmarks.value).forEach((folderName) => {
    folderExpanded.value[folderName] = false;
  });
};

const saveApiBaseUrl = async () => {
  await setApiBaseUrl(apiBaseUrl.value);
  localStorage.setItem("customBgUrl", bgUrl.value);
  showSettingsModal.value = false;
  window.location.reload();
};

const handleBgFileChange = (e) => {
  const file = e.target.files[0];
  if (!file) return;
  const reader = new FileReader();
  reader.onload = (evt) => {
    bgUrl.value = evt.target.result;
  };
  reader.readAsDataURL(file);
};

// 主题相关
const themes = [
  { label: "默认", value: "default-theme" },
  { label: "科技风", value: "tech-theme" },
];
const currentTheme = ref(localStorage.getItem("theme") || "default-theme");

function switchTheme(theme) {
  currentTheme.value = theme;
  localStorage.setItem("theme", theme);

  // 更新 body 和 app 元素的 class
  const app = document.getElementById("app");
  const body = document.body;

  // 移除所有主题 class
  app?.classList.remove("default-theme", "tech-theme");
  body.classList.remove("default-theme", "tech-theme");

  // 添加当前主题 class
  app?.classList.add(theme);
  body.classList.add(theme);

  // 触发自定义事件，通知其他组件主题已变化
  window.dispatchEvent(new CustomEvent("themeChanged"));
}

// 处理背景类型切换
function handleBgTypeChange(type) {
  bgType.value = type;
  localStorage.setItem("bgType", type);

  if (type === "theme") {
    // 切换到系统皮肤时，清除自定义背景
    bgUrl.value = "";
    localStorage.removeItem("customBgUrl");
    // 触发背景更新事件
    window.dispatchEvent(
      new CustomEvent("backgroundChanged", {
        detail: { type: "theme" },
      })
    );
  }
}

// 移除背景图
function removeBgImage() {
  bgUrl.value = "";
  localStorage.removeItem("customBgUrl");
  // 自动切换回系统皮肤
  handleBgTypeChange("theme");
}
</script>

<style scoped>
.search-section {
  padding: 4rem 1rem 2rem;
  width: 100%;
  max-width: 1000px;
  margin: 0 auto;
}

.search-wrapper {
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(30px);
  -webkit-backdrop-filter: blur(30px);
  border-radius: 50px;
  padding: 14px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1),
    inset 0 1px 0 rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.2);
  position: relative;
  transition: all 0.3s ease;
}

.search-wrapper:focus-within {
  background: rgba(255, 255, 255, 0.95);
  border-color: rgba(102, 126, 234, 0.4);
  box-shadow: 0 12px 40px rgba(102, 126, 234, 0.15),
    0 0 0 1px rgba(102, 126, 234, 0.2);
  transform: translateY(-2px);
  backdrop-filter: none;
  -webkit-backdrop-filter: none;
}

.search-engine-selector {
  display: flex;
  padding-right: 12px;
  border-right: 1px solid #e2e8f0;
}

.search-engine-selector button {
  background: none;
  border: 1px solid transparent;
  cursor: pointer;
  padding: 10px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.search-engine-selector button:hover {
  background: rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(10px);
  transform: translateY(-0.5px);
  transition: all 0.2s ease;
}

.search-engine-selector button.active {
  background: rgba(102, 126, 234, 0.15);
  backdrop-filter: blur(15px);
  color: #667eea;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2),
    inset 0 1px 0 rgba(255, 255, 255, 0.4);
  border: 1px solid rgba(102, 126, 234, 0.3);
}

.engine-icon {
  width: 22px;
  height: 22px;
}

.search-bar {
  flex: 1;
  display: flex;
  align-items: center;
}

.input-container {
  flex: 1;
  position: relative;
}

.search-input {
  width: 100%;
  border: none;
  outline: none;
  padding: 0 24px;
  font-size: 17px;
  background-color: transparent;
  color: #ffffff;
  transition: all 0.3s ease;
  line-height: 1.5;
}

.search-input:focus {
  color: #2d3748;
}

.search-input::placeholder {
  color: rgba(255, 255, 255, 0.7);
  font-weight: 400;
  transition: all 0.3s ease;
}

.search-input:focus::placeholder {
  color: #667eea;
  opacity: 0.7;
}

.search-button {
  background: transparent;
  color: rgba(255, 255, 255, 0.9);
  border: none;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  font-size: 17px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.search-button:hover {
  transform: translateY(-2px);
  color: #667eea;
}

.search-button.focused {
  transform: translateY(-2px);
  color: #667eea;
}

.bookmark-controls {
  padding-left: 12px;
}

.bookmark-btn {
  background: rgba(240, 147, 23, 0.8);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  cursor: pointer;
  width: 48px;
  height: 48px;
  border-radius: 50%;
  color: white;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8px 20px rgba(240, 147, 23, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.3);
  transition: all 0.3s ease;
}

.bookmark-btn:hover {
  background: rgba(240, 147, 23, 0.9);
  color: white;
  transform: translateY(-2px);
  box-shadow: 0 12px 25px rgba(240, 147, 23, 0.4),
    inset 0 1px 0 rgba(255, 255, 255, 0.4);
}

/* 建议下拉框 */
.suggestions-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08), 0 4px 16px rgba(0, 0, 0, 0.04);
  border: 1px solid rgba(255, 255, 255, 0.6);
  z-index: 1000;
  max-height: 400px;
  overflow-y: auto;
  overflow-x: hidden;
  margin-top: 8px;
  animation: dropdownSlideIn 0.25s ease-out;
}

@keyframes dropdownSlideIn {
  0% {
    opacity: 0;
    transform: translateY(-8px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

.suggestions-dropdown::-webkit-scrollbar {
  width: 4px;
}

.suggestions-dropdown::-webkit-scrollbar-track {
  background: transparent;
}

.suggestions-dropdown::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 2px;
}

.suggestions-dropdown::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.2);
}

.suggestions-header {
  padding: 12px 16px 8px;
  font-size: 11px;
  color: rgba(102, 126, 234, 0.8);
  font-weight: 600;
  background: rgba(248, 250, 252, 0.6);
  border-bottom: 1px solid rgba(226, 232, 240, 0.8);
  border-radius: 16px 16px 0 0;
  margin: -1px -1px 0 -1px;
}

.suggestion-types {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.suggestion-type {
  display: flex;
  align-items: center;
  gap: 4px;
  color: rgba(102, 126, 234, 0.8);
  background: rgba(102, 126, 234, 0.08);
  padding: 3px 8px;
  border-radius: 8px;
  font-size: 10px;
  transition: all 0.2s ease;
}

.suggestion-type:hover {
  background: rgba(102, 126, 234, 0.12);
  color: rgba(102, 126, 234, 0.9);
}

.no-suggestions {
  padding: 16px 18px;
  display: flex;
  align-items: center;
  gap: 12px;
  color: rgba(113, 128, 150, 0.8);
  font-size: 14px;
  background: rgba(248, 250, 252, 0.5);
  border-radius: 12px;
  margin: 8px 12px;
  font-weight: 500;
}

.no-suggestions .suggestion-icon {
  color: rgba(113, 128, 150, 0.6);
  background: rgba(113, 128, 150, 0.1);
  width: 18px;
  height: 18px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.suggestion-item {
  padding: 12px 16px;
  cursor: pointer;
  border-bottom: 1px solid rgba(226, 232, 240, 0.6);
  display: flex;
  align-items: center;
  gap: 12px;
  transition: all 0.2s ease;
  position: relative;
}

.suggestion-item:last-child {
  border-bottom: none;
  border-radius: 0 0 16px 16px;
}

.suggestion-item:hover,
.suggestion-item.active {
  background: rgba(102, 126, 234, 0.06);
  color: rgba(102, 126, 234, 0.9);
}

.suggestion-icon {
  color: rgba(102, 126, 234, 0.7);
  width: 16px;
  height: 16px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(102, 126, 234, 0.1);
  border-radius: 4px;
  transition: all 0.2s ease;
}

.suggestion-item:hover .suggestion-icon,
.suggestion-item.active .suggestion-icon {
  color: rgba(102, 126, 234, 0.9);
  background: rgba(102, 126, 234, 0.15);
}

.suggestion-content {
  flex: 1;
  min-width: 0;
}

.suggestion-title {
  font-weight: 600;
  color: rgba(26, 32, 44, 0.9);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 14px;
  transition: color 0.3s ease;
}

.suggestion-item:hover .suggestion-title,
.suggestion-item.active .suggestion-title {
  color: rgba(102, 126, 234, 0.9);
}

.suggestion-url {
  font-size: 11px;
  color: rgba(113, 128, 150, 0.7);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-top: 3px;
  transition: color 0.3s ease;
}

.suggestion-item:hover .suggestion-url,
.suggestion-item.active .suggestion-url {
  color: rgba(102, 126, 234, 0.6);
}

.suggestion-actions {
  display: flex;
  gap: 4px;
}

.remove-btn {
  background: rgba(239, 68, 68, 0.1);
  border: none;
  color: rgba(239, 68, 68, 0.7);
  cursor: pointer;
  padding: 4px 6px;
  border-radius: 4px;
  transition: all 0.2s ease;
  font-size: 11px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.remove-btn:hover {
  background: rgba(239, 68, 68, 0.15);
  color: rgba(239, 68, 68, 0.9);
}

/* 搜索栏响应式设计 */
@media (max-width: 768px) {
  .search-section {
    padding: 2rem 0.5rem 1rem;
    max-width: 95%;
  }

  .search-wrapper {
    padding: 12px;
    border-width: 1px;
  }

  .search-wrapper:focus-within {
    transform: translateY(-1px);
    background: rgba(255, 255, 255, 0.4);
    box-shadow: 0 8px 30px rgba(102, 126, 234, 0.15),
      0 0 0 1px rgba(102, 126, 234, 0.2), inset 0 1px 0 rgba(255, 255, 255, 0.5);
  }

  .search-input {
    font-size: 16px;
    padding: 0 20px;
  }

  .search-button {
    width: 46px;
    height: 46px;
    font-size: 16px;
  }

  .bookmark-btn {
    width: 46px;
    height: 46px;
    font-size: 16px;
  }

  .settings-btn-round {
    width: 46px;
    height: 46px;
    font-size: 16px;
  }
}

@media (max-width: 480px) {
  .search-section {
    max-width: 98%;
  }

  .search-wrapper {
    padding: 10px;
  }

  .search-input {
    font-size: 15px;
    padding: 0 18px;
  }

  .search-button {
    width: 44px;
    height: 44px;
    font-size: 15px;
  }

  .bookmark-btn {
    width: 44px;
    height: 44px;
  }

  .settings-btn-round {
    width: 44px;
    height: 44px;
  }
}

/* 设置icon圆形主色按钮 */
.settings-controls {
  margin-left: 8px;
  display: flex;
  align-items: center;
}
.settings-btn-round {
  background: rgba(102, 126, 234, 0.8);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: #fff;
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.3);
  cursor: pointer;
  transition: all 0.3s ease;
  margin-left: 8px;
  padding: 0;
}
.settings-btn-round i {
  font-size: 16px;
  line-height: 1;
  vertical-align: middle;
}
.settings-btn-round:hover {
  background: rgba(102, 126, 234, 0.9);
  transform: translateY(-2px);
  box-shadow: 0 12px 25px rgba(102, 126, 234, 0.4),
    inset 0 1px 0 rgba(255, 255, 255, 0.4);
}

/* 书签弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  padding: 20px;
}

.modal-content {
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
  width: 100%;
  max-width: 600px;
  max-height: 80vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  animation: modalFadeIn 0.3s ease;
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: scale(0.9) translateY(-20px);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

.modal-header {
  padding: 24px 24px 16px;
  border-bottom: 1px solid #e2e8f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #f8fafc;
}

.modal-header h3 {
  font-size: 1.5rem;
  font-weight: 600;
  color: #1a202c;
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #718096;
  padding: 8px;
  border-radius: 50%;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
}

.close-btn:hover {
  background: #e2e8f0;
  color: #4a5568;
}

.modal-body {
  padding: 24px;
  overflow-y: auto;
  flex: 1;
}

.bookmark-section {
  margin-bottom: 32px;
}

.bookmark-section:last-child {
  margin-bottom: 0;
}

.bookmark-section h4 {
  font-size: 1.1rem;
  font-weight: 600;
  color: #2d3748;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.import-controls,
.operation-controls,
.folder-controls {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  align-items: center;
}

.import-help {
  font-size: 0.875rem;
  color: #718096;
  margin-left: 8px;
}

.btn-primary,
.btn-secondary,
.btn-danger,
.btn-success,
.btn-outline {
  padding: 10px 16px;
  border: none;
  border-radius: 8px;
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 6px;
  text-decoration: none;
}

.btn-primary {
  background: #667eea;
  color: white;
}

.btn-primary:hover {
  background: #5a67d8;
  transform: translateY(-1px);
}

.btn-secondary {
  background: #718096;
  color: white;
}

.btn-secondary:hover {
  background: #4a5568;
  transform: translateY(-1px);
}

.btn-danger {
  background: #e53e3e;
  color: white;
}

.btn-danger:hover {
  background: #c53030;
  transform: translateY(-1px);
}

.btn-success {
  background: #38a169;
  color: white;
}

.btn-success:hover {
  background: #2f855a;
  transform: translateY(-1px);
}

.btn-outline {
  background: transparent;
  color: #4a5568;
  border: 1px solid #e2e8f0;
}

.btn-outline:hover {
  background: #f7fafc;
  border-color: #cbd5e0;
  transform: translateY(-1px);
}

.bookmark-list {
  overflow-y: visible;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  background: #f8fafc;
}

.folder-group {
  border-bottom: 1px solid #e2e8f0;
}

.folder-group:last-child {
  border-bottom: none;
}

.folder-header {
  padding: 12px 16px;
  background: #edf2f7;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 12px;
  transition: background-color 0.2s;
}

.folder-header:hover {
  background: #e2e8f0;
}

.folder-name {
  font-weight: 600;
  color: #2d3748;
  display: flex;
  align-items: center;
  gap: 8px;
}

.folder-count {
  font-size: 0.75rem;
  color: #718096;
  background: #cbd5e0;
  padding: 2px 6px;
  border-radius: 10px;
}

.folder-toggle {
  color: #718096;
  transition: transform 0.2s;
}

.folder-toggle.expanded {
  transform: rotate(45deg);
}

.folder-content {
  background: white;
}

.bookmark-item {
  padding: 12px 16px;
  border-bottom: 1px solid #f1f5f9;
  display: flex;
  align-items: center;
  justify-content: space-between;
  transition: background-color 0.2s;
}

.bookmark-item:last-child {
  border-bottom: none;
}

.bookmark-item:hover {
  background: #f8fafc;
}

.bookmark-info {
  flex: 1;
  min-width: 0;
}

.bookmark-title {
  font-weight: 500;
  color: #1a202c;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.bookmark-url {
  font-size: 0.75rem;
  color: #718096;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.bookmark-actions {
  display: flex;
  gap: 4px;
  margin-left: 12px;
}

.action-btn {
  background: none;
  border: none;
  color: #718096;
  cursor: pointer;
  padding: 6px;
  border-radius: 4px;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
}

.action-btn:hover {
  background: #e2e8f0;
  color: #4a5568;
}

.action-btn.remove:hover {
  background: #fed7d7;
  color: #e53e3e;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .modal-content {
    max-width: 95vw;
    max-height: 90vh;
  }

  .modal-header,
  .modal-body {
    padding: 16px;
  }

  .import-controls,
  .operation-controls,
  .folder-controls {
    flex-direction: column;
    align-items: stretch;
  }

  .btn-primary,
  .btn-secondary,
  .btn-danger,
  .btn-success,
  .btn-outline {
    justify-content: center;
  }

  .bookmark-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .bookmark-actions {
    margin-left: 0;
    align-self: flex-end;
  }
}

/* 设置弹窗样式 */
.settings-modal {
  background: #fff;
  border-radius: 22px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.18);
  width: 95vw;
  max-width: 420px;
  max-height: 92vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  animation: fadeInUp 0.3s;
}
@keyframes fadeInUp {
  from {
    transform: translateY(40px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}
.settings-modal-header {
  padding: 28px 32px 10px 32px;
  border-bottom: 1px solid #f0f1f5;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #f8fafd;
}
.settings-modal-title {
  font-size: 2rem;
  font-weight: 900;
  color: #23233a;
  letter-spacing: 1px;
  display: flex;
  align-items: center;
  gap: 10px;
}
.settings-modal-close {
  background: none;
  border: none;
  font-size: 22px;
  cursor: pointer;
  color: #b0b3c6;
  padding: 6px;
  border-radius: 50%;
  transition: background 0.18s;
}
.settings-modal-close:hover {
  background: #f0f1f5;
  color: #23233a;
}
.settings-modal-body {
  padding: 32px 32px 24px 32px;
  overflow-y: auto;
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 36px;
}
.settings-group {
  background: #f7f8fa;
  border-radius: 16px;
  padding: 22px 20px 18px 20px;
  margin-bottom: 0;
  box-shadow: 0 2px 8px #e1e5e922;
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.settings-label {
  font-size: 1.13rem;
  font-weight: 700;
  color: #2a2a3a;
  margin-bottom: 8px;
  letter-spacing: 0.5px;
}
.settings-input {
  background: #f4f6fb;
  border: 1.5px solid #e1e5e9;
  font-size: 1.13rem;
  padding: 14px 16px;
  border-radius: 12px;
  margin-bottom: 0;
  transition: border-color 0.2s, box-shadow 0.2s;
  outline: none;
}
.settings-input:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 2px #667eea22;
  background: #fff;
}
.settings-upload-btn {
  width: 100%;
  border-radius: 10px;
  background: #f0f0f0;
  color: #333;
  font-size: 1rem;
  margin-bottom: 0;
  padding: 12px 0;
  font-weight: 600;
  border: none;
  transition: background 0.18s;
}
.settings-upload-btn:hover {
  background: #e2e8f0;
}
.settings-bg-preview {
  margin: 10px 0 0 0;
  text-align: center;
}
.settings-bg-preview img {
  max-width: 100%;
  max-height: 120px;
  border-radius: 12px;
  box-shadow: 0 2px 12px #0001;
  border: 1.5px solid #e1e5e9;
  object-fit: cover;
}
.settings-save-btn {
  width: 100%;
  border-radius: 12px;
  background: linear-gradient(90deg, #667eea, #5a67d8);
  color: #fff;
  font-size: 1.15rem;
  font-weight: 700;
  padding: 15px 0;
  box-shadow: 0 2px 8px #667eea22;
  border: none;
  margin-top: 10px;
  transition: background 0.2s;
}
.settings-save-btn:hover {
  background: linear-gradient(90deg, #5a67d8, #667eea);
}
@media (max-width: 600px) {
  .settings-modal {
    max-width: 98vw;
    border-radius: 0 0 18px 18px;
  }
  .settings-modal-header,
  .settings-modal-body {
    padding-left: 12px;
    padding-right: 12px;
  }
  .settings-modal-header {
    padding-top: 18px;
    padding-bottom: 6px;
  }
  .settings-modal-body {
    padding-top: 18px;
    padding-bottom: 18px;
    gap: 22px;
  }
  .settings-group {
    padding: 14px 8px 10px 8px;
    border-radius: 10px;
    gap: 10px;
  }
  .settings-modal-title {
    font-size: 1.3rem;
  }
}

.search-engine-selector button + button {
  margin-left: 10px;
}

.theme-options {
  display: flex;
  gap: 10px;
  margin-top: 8px;
}

.theme-select-btn {
  padding: 8px 16px;
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  background: rgba(255, 255, 255, 0.1);
  color: #333;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
}

.theme-select-btn:hover {
  background: rgba(102, 126, 234, 0.1);
  border-color: rgba(102, 126, 234, 0.3);
}

.theme-select-btn.active {
  background: rgba(102, 126, 234, 0.2);
  border-color: rgba(102, 126, 234, 0.4);
  color: #667eea;
}

.background-options {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.option-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.radio-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: 14px;
}

.radio-label input[type="radio"] {
  margin: 0;
  cursor: pointer;
}

.theme-options {
  display: flex;
  gap: 10px;
  margin-left: 24px;
}

.custom-bg-options {
  margin-left: 24px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.settings-bg-preview {
  position: relative;
  margin-top: 8px;
  border-radius: 8px;
  overflow: hidden;
}

.settings-bg-preview img {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 8px;
}

.remove-bg-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.5);
  border: none;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.remove-bg-btn:hover {
  background: rgba(0, 0, 0, 0.7);
}

.settings-upload-btn {
  align-self: flex-start;
}
</style>
